<template>
  <div>
    <div>
      <div>
        <el-tabs v-model="activeName" type="card" :before-leave="handleBeforeLeave">
          <el-tab-pane label="章节管理" name="first">
            <chapter-management v-model="dirList" @preview="handlePreview" @updateFileList="handleUpdateFileList" />
          </el-tab-pane>
          <el-tab-pane label="数字人视频" name="second">
            <digital-human-video :course-id="postForm.id" ref="digitalHumanVideo" />
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 文件预览对话框 -->
      <file-preview-dialog :visible.sync="previewVisible" :preview-data="previewData" />

      <!-- 知识点抽取对话框 -->
      <knowledge-extract-dialog :visible.sync="extrVisible" :course-id="postForm.id" ref="knowledgeExtract" />

      <!-- 批量操作对话框 -->
      <batch-operation-dialog :visible.sync="batchVisible" :dir-list="dirList" @batch-update="handleBatchUpdate" />

      <!-- 导入对话框 -->
      <import-dialog :visible.sync="catDialog" :excludes="excludes" @import="handleImport" />

      <!-- 无访问权限提示 -->
      <el-dialog :visible.sync="noAccessDialogVisible" width="360px" :show-close="false" center>
        <div style="text-align: center; font-size: 16px">请联系管理员</div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="noAccessDialogVisible = false">关闭</el-button>
        </span>
      </el-dialog>
    </div>

    <!-- 文件预览对话框 -->
    <file-preview-dialog :visible.sync="previewVisible" :preview-data="previewData" />

    <!-- 知识点抽取对话框 -->
    <knowledge-extract-dialog :visible.sync="extrVisible" :course-id="postForm.id" ref="knowledgeExtract" />

    <!-- 批量操作对话框 -->
    <batch-operation-dialog :visible.sync="batchVisible" :dir-list="dirList" @batch-update="handleBatchUpdate" />

    <!-- 导入对话框 -->
    <import-dialog :visible.sync="catDialog" :excludes="excludes" @import="handleImport" />

    <!-- 无访问权限提示 -->
    <el-dialog :visible.sync="noAccessDialogVisible" width="360px" :show-close="false" center>
      <div style="text-align: center; font-size: 16px">请联系管理员</div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="noAccessDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { uuid } from 'vue-uuid'
import { mapGetters } from 'vuex'
import { fetchFile } from '@/api/course/file'

// 导入自定义组件
import ChapterManagement from './ChapterManagement.vue'
import DigitalHumanVideo from './DigitalHumanVideo.vue'
import FilePreviewDialog from './FilePreviewDialog.vue'
import KnowledgeExtractDialog from './KnowledgeExtractDialog.vue'
import BatchOperationDialog from './BatchOperationDialog.vue'
import ImportDialog from './ImportDialog.vue'

export default {
  name: 'DirList',
  pageState: 'dirList',
  components: {
    ChapterManagement,
    DigitalHumanVideo,
    FilePreviewDialog,
    KnowledgeExtractDialog,
    BatchOperationDialog,
    ImportDialog
  },
  props: {
    value: {
      type: Array,
      default: () => []
    },
    props: {
      value: {
        type: Array,
        default: () => []
      },
      isDigitalHuman: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        activeName: 'first', // 默认选中章节管理标签
        dirList: [],
        excludes: [],
        noAccessDialogVisible: false,

        // 对话框控制变量
        previewVisible: false,
        extrVisible: false,
        batchVisible: false,
        catDialog: false,

        // 预览数据
        previewData: {},

        // 表单数据
        postForm: {
          id: null
        },

        // 临时ID
        tempId: `temp_${uuid.v4()}`
      }
    },
    computed: {
      ...mapGetters(['zlBaseUrl'])
    },
    watch: {
      value: {
        handler(val) {
          this.dirList = val
        },
        deep: true,
        immediate: true
      },
      dirList: {
        handler(val) {
          this.$emit('input', val)
          this.processExcludes()
        },
        deep: true
      }
    },
    created() {
      this.dirList = this.value
      this.getCourseIdFromUrl()
    },
    methods: {
      // 标签切换前拦截，校验数字人视频访问权限
      handleBeforeLeave(newName, oldName) {
        if (newName === 'second') {
          const userId = window.sessionStorage.getItem('id')
          if (userId !== '10001') {
            this.noAccessDialogVisible = true
            return false
          }
        }
        return true
      },
      // 获取URL中的课程ID
      getCourseIdFromUrl() {
        const url = window.location.href
        const match = url.match(/\/update\/(\d+)/)
        if (match && match[1]) {
          this.postForm.id = match[1]
          console.log('从URL中获取课程ID：', this.postForm.id)
        }
      },

      // 处理文件预览
      handlePreview(data) {
        this.previewVisible = true
        this.previewData = {
          fileType: data.fileType,
          viewUrl: data.viewUrl || data.fileUrl,
          fileUrl: data.fileUrl,
          id: data.id
        }
      },

      // 处理批量更新
      handleBatchUpdate(updateData) {
        for (let i = 0; i < this.dirList.length; i++) {
          const fileList = this.dirList[i].fileList
          if (fileList.length > 0) {
            for (let j = 0; j < fileList.length; j++) {
              if (updateData.needLearnCk) {
                fileList[j].needLearn = updateData.needLearn
              }
              if (updateData.pointsCk) {
                fileList[j].points = updateData.points
              }
            }
          }
        }
        this.$forceUpdate()
      },

      // 打开批量操作对话框
      batchDialog() {
        this.batchVisible = true
      },

      // 打开导入对话框
      importCat() {
        this.catDialog = true
      },

      // 处理导入请求
      handleImport(importForm) {
        fetchFile(importForm).then(res => {
          for (let i = 0; i < res.data.length; i++) {
            const dir = res.data[i]
            this.dirList.push(dir)
          }
        })
      },

      // 处理知识点抽取
      showExtr(item) {
        this.$refs.knowledgeExtract.showExtr(item)
      },

      // 处理文件列表更新
      handleUpdateFileList(val) {
        this.$emit('updateFileList', val)
      },

      // 处理文件排除列表
      processExcludes() {
        const ids = []
        for (let i = 0; i < this.dirList.length; i++) {
          const files = this.dirList[i].fileList
          for (let j = 0; j < files.length; j++) {
            ids.push(files[j].fileId)
          }
        }
        this.excludes = ids
      },

      // 图谱检查
      checkGraph() {
        if (this.dirList.length <= 0) {
          this.$message.error('请先进行知识点抽取')
          return
        }
        this.$refs.knowledgeExtract.iframeUrl = `${this.zlBaseUrl}/#/navigation/displayGraph1?courseId=${this.postForm.id}`
        this.extrVisible = true
      },

      // 显示知识类目上传
      showZLUpload() {
        this.$refs.knowledgeExtract.showZLUpload()
      }
    }
  },
  data() {
    return {
      activeName: 'first', // 默认选中章节管理标签
      dirList: [],
      excludes: [],
      noAccessDialogVisible: false,

      // 对话框控制变量
      previewVisible: false,
      extrVisible: false,
      batchVisible: false,
      catDialog: false,

      // 预览数据
      previewData: {},

      // 表单数据
      postForm: {
        id: null
      },

      // 临时ID
      tempId: `temp_${uuid.v4()}`
    }
  },
  computed: {
    ...mapGetters(['zlBaseUrl'])
  },
  watch: {
    value: {
      handler(val) {
        this.dirList = val
      },
      deep: true,
      immediate: true
    },
    dirList: {
      handler(val) {
        this.$emit('input', val)
        this.processExcludes()
      },
      deep: true
    }
  },
  created() {
    this.dirList = this.value
    this.getCourseIdFromUrl()
  },
  methods: {
    // 标签切换前拦截，校验数字人视频访问权限
    handleBeforeLeave(newName, oldName) {
      if (newName === 'second') {
        const userId = window.sessionStorage.getItem('id')
        if (userId !== '10001') {
          this.noAccessDialogVisible = true
          return false
        }
      }
      return true
    },
    // 获取URL中的课程ID
    getCourseIdFromUrl() {
      const url = window.location.href
      const match = url.match(/\/update\/(\d+)/)
      if (match && match[1]) {
        this.postForm.id = match[1]
        console.log('从URL中获取课程ID：', this.postForm.id)
      }
    },

    // 处理文件预览
    handlePreview(data) {
      this.previewVisible = true
      this.previewData = {
        fileType: data.fileType,
        viewUrl: data.viewUrl || data.fileUrl,
        fileUrl: data.fileUrl,
        id: data.id
      }
    },

    // 处理批量更新
    handleBatchUpdate(updateData) {
      for (let i = 0; i < this.dirList.length; i++) {
        const fileList = this.dirList[i].fileList
        if (fileList.length > 0) {
          for (let j = 0; j < fileList.length; j++) {
            if (updateData.needLearnCk) {
              fileList[j].needLearn = updateData.needLearn
            }
            if (updateData.pointsCk) {
              fileList[j].points = updateData.points
            }
          }
        }
      }
      this.$forceUpdate()
    },

    // 打开批量操作对话框
    batchDialog() {
      this.batchVisible = true
    },

    // 打开导入对话框
    importCat() {
      this.catDialog = true
    },

    // 处理导入请求
    handleImport(importForm) {
      fetchFile(importForm).then(res => {
        for (let i = 0; i < res.data.length; i++) {
          const dir = res.data[i]
          this.dirList.push(dir)
        }
      })
    },

    // 处理知识点抽取
    showExtr(item) {
      this.$refs.knowledgeExtract.showExtr(item)
    },

    // 处理文件列表更新
    handleUpdateFileList(val) {
      this.$emit('updateFileList', val)
    },

    // 处理文件排除列表
    processExcludes() {
      const ids = []
      for (let i = 0; i < this.dirList.length; i++) {
        const files = this.dirList[i].fileList
        for (let j = 0; j < files.length; j++) {
          ids.push(files[j].fileId)
        }
      }
      this.excludes = ids
    },

    // 图谱检查
    checkGraph() {
      if (this.dirList.length <= 0) {
        this.$message.error('请先进行知识点抽取')
        return
      }
      this.$refs.knowledgeExtract.iframeUrl = `${this.zlBaseUrl}/#/navigation/displayGraph1?courseId=${this.postForm.id}`
      this.extrVisible = true
    },

    // 显示知识类目上传
    showZLUpload() {
      this.$refs.knowledgeExtract.showZLUpload()
    }
  }
}
</script>

<style scoped lang="scss">
/deep/.el-button--success {
  background-color: #6f5af6 !important;
  border-color: #6f5af6 !important;
  position: relative;
}

/deep/.el-button--success:active {
  background-color: #501fe3 !important;
  border-color: #501fe3 !important;
}
</style>
